package servlet;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.joor.Reflect;

import dao.ContentsDAO;
import entity.Contents;

/**
 * @author 
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
@WebServlet("/draft")
public class DraftServlet extends HttpServlet {
    private ContentsDAO dao = new ContentsDAO();
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
       
       String savePath = this.getServletContext().getRealPath("/upload");
       File file = new File(savePath);
       if (!file.exists() && !file.isDirectory()) {
           System.out.println(savePath+"目录不存在，需要创建");
           file.mkdir();
       }
       //消息提示
       String message = "";
       String filepath="";
       Contents contents = new Contents();
       try{
           DiskFileItemFactory factory = new DiskFileItemFactory();
           ServletFileUpload upload = new ServletFileUpload(factory);
           upload.setHeaderEncoding("UTF-8"); 
           List<FileItem> list = upload.parseRequest(request);
          for(FileItem item : list){
              if(item.isFormField()){
            	   
                  String name = item.getFieldName();
                  String value = item.getString("UTF-8");
                  contents =set(contents,name,value);
                  System.out.println(name + "=" + value);
              }else{
                  String filename = item.getName();
                  System.out.println(filename);
                  if(filename==null || filename.trim().equals("")){
                      continue;
                  }
                   filename = filename.substring(filename.lastIndexOf("\\")+1);
                   InputStream in = item.getInputStream();
                   FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
                 byte buffer[] = new byte[1024];
                 int len = 0;
                 while((len=in.read(buffer))>0){
                     out.write(buffer, 0, len);
                   }
                   in.close();
                   out.close();
                   item.delete();
                   message = "文件上传成功！";
                   contents.setOther(filename);
               }
           }
       }catch (Exception e) {
           message= "文件上传失败！";
           e.printStackTrace();
           
       }
       request.setAttribute("message",message);

       request.setCharacterEncoding("utf-8");
       String result =addcontentsresult(request,contents);
       RequestDispatcher dispatcher = request.getSession().getServletContext()
               .getRequestDispatcher(result);
       if (dispatcher != null)
           dispatcher.forward(request, response);
    }
    
    

	private Contents set(Contents contents, String name, String value) {
		Reflect.on(contents).set(name, value);  
		return contents;
	}



	private String list(HttpServletRequest request) {
        try {
            request.setAttribute("objlist",dao.loadAllContents());
            return "/draftList.jsp";
        } catch (Exception ex) {
            request.setAttribute("errormsg", ex.getMessage());
            return "/error.jsp";
        }
    }

    private String addcontents(HttpServletRequest request) {
        request.setAttribute("obj", new Contents());
        return "/draftList.jsp?userno='"+request.getParameter("userno")+"'";
    }

    private String addcontentsresult(HttpServletRequest request,Contents contents) {
        try {
            this.dao.addContents(contents);
            return this.list(request);
        } catch (Exception ex) {
            request.setAttribute("errormsg", ex.getMessage());
            return "/error.jsp";
        }

    }
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    	doGet(request, response);
    }
    
    public void destroy() {
        // TODO Auto-generated method stub
        dao.release();
        super.destroy();
    }

}
